import { defineStore } from "pinia";
import {
  login,
  register,
  getUserInfo,
  sendEmailCode,
  logout,
  getUserDetailInfo,
  getUnreadMessageCount,
} from "@/api/user";
import { message } from "@/utils/message";

const userStore = defineStore("userStore", {
  state: (): UserState => ({
    token: undefined,
    userInfo: undefined,
    userDetailInfo: undefined,
    unreadMessageCount: 0,
  }),
  actions: {
    async handleLogin(data: LoginForm) {
      const result = await login(data);
      if (result.data.code === 200) {
        message({
          type: "success",
          message: "登录成功",
          duration: 2000,
        });
        localStorage.setItem("token", result.data.data);
        location.reload();
      }
    },
    async handleRegister(data: RegisterForm) {
      const result = await register(data);
      if (result.data.code === 200) {
        message({
          type: "success",
          duration: 2000,
          message: "注册成功!",
        });
        localStorage.setItem("token", result.data.data);
        location.reload();
      }
    },
    async handleLogout() {
      const result = await logout();
      if (result.data.code === 200) {
        message({
          type: "success",
          duration: 2000,
          message: "退出登录成功",
        });
        this.userInfo = undefined;
        localStorage.removeItem("userInfo");
        localStorage.removeItem("token");
        location.href = "/";
      }
    },

    async handleSendEmailCode(email: string) {
      const result = await sendEmailCode(email);
      if (result.data.code === 200) {
        message({
          type: "success",
          message: "验证码发送成功",
          duration: 2000,
        });
      }
    },
    async handleGetUserInfo() {
      const result = await getUserInfo();
      if (result.data.code === 200) {
        this.userInfo = result.data.data;
        localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
        const messageCount = await getUnreadMessageCount();
        if (messageCount.data.code === 200) {
          this.unreadMessageCount = messageCount.data.data;
        }
        return;
      }
      this.userInfo = undefined;
      localStorage.removeItem("token");
      localStorage.removeItem("userInfo");
    },
    async handleGetUserDetailInfo() {
      const result = await getUserDetailInfo();
      if (result.data.code === 200) {
        this.userDetailInfo = result.data.data;
      }
    },
  },
});

export default userStore;
